package com.mab.mall.cart.controller;

import com.mab.mall.cart.interceptor.AuthInterceptor;
import com.mab.mall.cart.service.ICartService;
import com.mab.mall.cart.vo.Cart;
import com.mab.mall.cart.vo.CartItem;
import com.msb.common.vo.MemberVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {

    @Autowired
    ICartService cartService;

    @GetMapping("/getUserCarItems")
    @ResponseBody
    public List<CartItem> getUserCarItems() {
        return  cartService.getUserCarItems();
    }
    @GetMapping("/cartList")
    public String queryCarList(HttpServletRequest request,Model model) {
        MemberVO memberVO = AuthInterceptor.threadLocal.get();
        Cart cart = cartService.getCarList();
        model.addAttribute("cart",cart);
        return "/cartList";
    }


    @GetMapping("/addCart")
    public String addCart(@RequestParam("skuId") Long  skuId,
                          @RequestParam("num")  Integer num,
                            Model model) {
       //把商品加到购物车里
        CartItem cartItem = null;
        try {
            cartItem = cartService.addCart(skuId,num);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        model.addAttribute("item",cartItem);
        return "/success";
    }

}
